package io.renren.modules.demo.service.impl;

import io.renren.common.exception.RRException;
import io.renren.common.utils.ExcelReaderUtil;
import io.renren.common.utils.R;
import io.renren.modules.demo.dao.GoodsDao;
import io.renren.modules.demo.entity.GoodsEntity;
import io.renren.modules.demo.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service("goodsService")
public class GoodsServiceImpl implements GoodsService {
	@Autowired
	private GoodsDao goodsDao;
	
	@Override
	public GoodsEntity queryObject(Long goodsId){
		return goodsDao.queryObject(goodsId);
	}
	
	@Override
	public List<GoodsEntity> queryList(Map<String, Object> map){
		return goodsDao.queryList(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return goodsDao.queryTotal(map);
	}
	
	@Override
	public void save(GoodsEntity goods){
		goodsDao.save(goods);
	}
	
	@Override
	public void update(GoodsEntity goods){
		goodsDao.update(goods);
	}
	
	@Override
	public void delete(Long goodsId){
		goodsDao.delete(goodsId);
	}
	
	@Override
	public void deleteBatch(Long[] goodsIds){
		goodsDao.deleteBatch(goodsIds);
	}

    /**
     * 解析excel保存数据库
     * @param file
     * @return
     */
	@Override
	public R exportExcel(MultipartFile file) {

        try {
            ArrayList<ArrayList<String>> al = ExcelReaderUtil.excelReader(file,1,5,3,4);
            for(int i=1;i<al.size();i++){
                ArrayList<String> alRow =  al.get(i);
                GoodsEntity goods = new GoodsEntity();
                goods.setName(alRow.get(0));
                goods.setIntro(alRow.get(1));
                goods.setPrice(new BigDecimal(alRow.get(2)));
                goods.setNum(Integer.parseInt(alRow.get(3)));
                goodsDao.save(goods);

                System.out.print("第"+i+"行数据：");
                for (int j = 0;j<alRow.size();j++){
                    System.out.print(alRow.get(j)+",");
                }
                System.out.println("");
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RRException("上传文件异常:"+e.getMessage());
        }
		return R.ok();
	}

}
